package com.wolves.career.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wolves.career.entity.UserPermissionsAccount;
import com.wolves.career.entity.UserPermissionsAdmin;
import com.wolves.career.entity.UserPermissionsAuthorization;
import com.wolves.career.entity.vo.QueryPermissionsAccount;
import com.wolves.career.service.UserPermissionsAccountService;
import com.wolves.career.service.UserPermissionsAdminService;
import com.wolves.career.service.UserPermissionsAuthorizationService;
import com.wolves.career.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 * 管理员模块
 * 管理员：管理维护人员的权限 + 管理用户信息
 *
 * @author 麦翔盛
 * @since 2021-10-19
 */
@RestController
@RequestMapping("/info/admin")
@CrossOrigin
public class UserPermissionsAdminController {
    @Autowired
    private UserPermissionsAdminService userPermissionsAdminService;
    @Autowired
    private UserPermissionsAccountService userPermissionsAccountService;
    @Autowired
    private UserPermissionsAuthorizationService userPermissionsAuthorizationService;

    /**
     * 管理员登录
     *
     * @param adminAccount   管理员账号
     * @param adminPasswored 管理员密码
     * @return
     */
    @GetMapping("/login/{adminAccount}/{adminPasswored}")
    public R login(@PathVariable("adminAccount") String adminAccount,
                   @PathVariable("adminPasswored") String adminPasswored) {
        if (adminAccount == null && adminAccount == "") {
            return R.error().message("用户名为空");
        }
        if (adminPasswored == null && adminPasswored == "") {
            return R.error().message("密码为空");
        }
        UserPermissionsAdmin admin = userPermissionsAdminService.check(adminAccount, adminPasswored);
        if (admin == null) {
            return R.error().message("用户名或密码错误");
        }
        return R.ok().data("Admin", admin);
    }

    /**
     * 更改密码
     *
     * @param adminAccount 管理员账号
     * @param oldPassword  管理员旧密码
     * @param newPassword  管理员新密码
     * @return
     */
    @PutMapping("/updatePassword/{adminAccount}/{oldPassword}/{newPassword}")
    public R updatePassword(@PathVariable("adminAccount") String adminAccount,
                            @PathVariable("oldPassword") String oldPassword,
                            @PathVariable("newPassword") String newPassword) {

        UserPermissionsAdmin admin = userPermissionsAdminService.check(adminAccount, oldPassword);
        if (admin == null) {
            //判断旧密码是否正确
            return R.error().message("密码错误");
        }
        Boolean update = userPermissionsAdminService.updatePassword(adminAccount, oldPassword, newPassword);
        if (!update) {
            //判断密码是否重复
            return R.error().message("新旧密码重复");
        }
        return R.ok().data("success", true);
    }

    /**
     * 分页查询用户信息
     *
     * @param pageNo                  第几页
     * @param limit                   每一页限制数据量
     * @param queryPermissionsAccount 封装对象
     * @return 返回当前页数据 以及 数据总数
     */
    @PostMapping("/pageInfo/{pageNo}/{limit}")
    public R pageInfo(@PathVariable("pageNo") long pageNo,
                      @PathVariable("limit") long limit,
                      @RequestBody(required = false) QueryPermissionsAccount queryPermissionsAccount) {
        //创建分页对象
        Page<UserPermissionsAccount> page = new Page<>(pageNo, limit);
        //获取条件对象
        QueryWrapper<UserPermissionsAccount> queryWrapper =
                userPermissionsAccountService.getPermissionsAccountQueryWrapper(queryPermissionsAccount);
        //获取分页信息
        IPage<UserPermissionsAccount> accountPage = userPermissionsAccountService.page(page, queryWrapper);
        //获取分页数据
        List<UserPermissionsAccount> records = accountPage.getRecords();
        //获取分页总数
        long total = accountPage.getTotal();
        //返回分页信息 和 分页数量
        return R.ok().data("records", records).data("total", total);
    }

    /**
     * 更新用户账号信息
     *
     * @param userPermissionsAccount 账号类
     * @return 成功data中返回一个success属性为true
     */
    @PutMapping("/updateUserInfo")
    public R updateUserInfo(@RequestBody(required = true) UserPermissionsAccount userPermissionsAccount) {
        boolean update = userPermissionsAccountService.update(userPermissionsAccount, null);
        if (!update) {
            return R.error().message("更新失败").data("success", false);
        }
        return R.ok().data("success", true);
    }

    /**
     * 根据账户id删除用户
     *
     * @param accountId 账户id
     * @return 成功data中返回一个success属性为true
     */
    @DeleteMapping("/deleteUser/{accountId}")
    public R deleteUser(@PathVariable("accountId") String accountId) {
        boolean remove = userPermissionsAccountService.removeById(accountId);
        if (!remove) {
            return R.error().message("删除失败").data("success", false);
        }
        return R.ok().data("success", remove);
    }

    /**
     * 保存用户
     *
     * @param user 账号类
     * @return 成功data中返回一个success属性为true
     */
    @PostMapping("/saveUser")
    public R saveUser(@RequestBody(required = true) UserPermissionsAccount user) {
        boolean save = userPermissionsAccountService.save(user);
        if (!save) {
            return R.error().message("添加失败").data("success", false);
        }
        return R.ok().data("success", save);
    }

    /**
     * 返回所有授权信息列表
     *
     * @return 成功data中返回一个success属性为true
     */
    @GetMapping("/getAuthorization")
    public R getAuthorization() {
        List<UserPermissionsAuthorization> list = userPermissionsAuthorizationService.list(null);
        return R.ok().data("list", list);
    }

    /**
     * 根据维护人员id和授权信息添加授权
     *
     * @param accountId
     * @param permissionsNo
     * @return 成功data中返回一个success属性为true
     */
    @PostMapping("/addAuthorization/{accountId}/{permissionsNo}")
    public R addAuthorization(@PathVariable("accountId") String accountId,
                              @PathVariable("permissionsNo") String permissionsNo) {
        //判断该人员是否是维护人员
        Boolean isMP = userPermissionsAccountService.isMaintenancePersonnel(accountId);
        if (!isMP) {
            return R.error().message("不是维护人员");
        }
        //判断是否已经授权
        boolean exist = userPermissionsAuthorizationService
                .existAuthorization(accountId, permissionsNo);
        if (exist) {
            return R.error().message("已经存在该授权").data("success", false);
        }
        return R.ok().data("success", true);
    }

    /**
     * 更新授权
     *
     * @param authorization 授权类
     * @return 成功data中返回一个success属性为true
     */
    @PostMapping("/updateAuthorization")
    public R updateAuthorization(@RequestBody(required = true)
                                         UserPermissionsAuthorization authorization) {
        boolean update = userPermissionsAuthorizationService.update(authorization, null);
        if (!update) {
            return R.error().message("更新失败").data("success", false);
        }
        return R.ok().data("success", true);
    }

    /**
     * 删除授权
     * @param accountId 维护人员id
     * @param permissionsNo 权限id
     * @return
     */
    @DeleteMapping("/addAuthorization/{accountId}/{permissionsNo}")
    public R deleteAuthorization(@PathVariable("accountId") String accountId,
                                 @PathVariable("permissionsNo") String permissionsNo) {
        QueryWrapper<UserPermissionsAuthorization> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("permissions_id", permissionsNo);
        boolean remove = userPermissionsAuthorizationService.remove(queryWrapper);
        if (!remove) {
            return R.error().message("删除失败").data("success", remove);
        }
        return R.ok().data("success", remove);
    }

}

